<style lang="less">
.title-text span {
  display: block; /*设置为块级元素会独占一行形成上下居中的效果*/
  position: relative; /*定位横线（当横线的父元素）*/

  color: black; /*居中文字的颜色*/
  font-weight: bold;
  text-align: center;
}

.title-text span:before,
.title-text span:after {
  content: "";
  position: absolute; /*定位背景横线的位置*/
  top: 50%;
  background: #dfdfdf; /*背景横线颜色*/
  width: 44%; /*单侧横线的长度*/
  height: 1px;
}

.title-text span:before {
  left: 0; /*调整背景横线的左右距离*/
}

.title-text span:after {
  right: 0;
}
.ivu-select-dropdown-list {
    height: 200px;
    overflow-y: auto;

}
.btns{
        background-color: white;
        padding: 20px 0 0 0;
    }
.channelClick{
        padding-bottom: 16px;
        display: flex;
        flex-flow: row;
        justify-content: flex-end;
        align-items: center;
    }
</style>
<template >
  <div class="search" style="background-color: rgb(255,255,255)">
    <Row class="btns">
      <i-col class="channelClick">  
        <Button @click="handleBack"  :size="buttonSize" label="large" type="primary" style="margin-right: 24px;" >返回</Button>
        <!-- <Button @click="joinBlack" :size="buttonSize" v-if="this.modalType == 3" label="large" type="primary" style="margin-right: 24px;" >申请黑名单</Button> -->
        <Button @click="handleCommit('companyForm')" v-if="this.modalType != 3" :size="buttonSize" label="large" type="primary" style="margin-right: 24px;" >提交</Button>
        <Button @click="handle('companyForm')"      v-if="this.modalType != 3" :size="buttonSize" label="large" type="primary" style="margin-right: 24px;" >保存</Button>
      </i-col>
    </Row>
    <div class="addInfo" style="display: block" id="thirdCompany">
      <h2 class="title-text">
        <span id="gkType">见证人信息</span>
      </h2>
      <Row style="margin-top: 1%;border: 1px solid #dcdee2; border-color: #e8eaec;    margin: 8px;">
        <Form ref="companyForm" :model="companyForm" :rules="ruleValidate" :label-width="140">
          <Row style="padding-top: 11px">
            <i-col span="12">
              <FormItem label="SP名称" prop="channelId" style="margin-left: 40%">
                <Select v-model="companyForm.channelId" disabled  filterable 
                  style="    width: 200px;" size="default">
                  <Option v-for="item in baseInfo" :value="item.id" :key="item.id">{{ item.channelFullName }}</Option>
                </Select>
              </FormItem>
            </i-col>
            <i-col span="12"  v-if="this.modalType!=3">
              <FormItem label="业务类型" prop="businessAttributes" style="margin-left: 10%">
                <RadioGroup v-model="companyForm.businessAttributes" size="default">
                  <Radio label="0" v-bind:disabled="companyForm.disabledNew" companyForm.businessAttributes>新车</Radio>
                  <Radio label="1" v-bind:disabled="companyForm.disabledOld" companyForm.businessAttributes>二手车</Radio>
                </RadioGroup>
              </FormItem>
            </i-col>

            <i-col span="12" v-if="this.modalType==3">
              <FormItem label="业务类型" prop="businessAttributes" style="margin-left: 10%">
                <RadioGroup v-model="companyForm.businessAttributes" size="default">
                  <Radio label="0" disabled companyForm.businessAttributes>新车</Radio>
                  <Radio label="1" disabled companyForm.businessAttributes>二手车</Radio>
                </RadioGroup>
              </FormItem>
            </i-col>
          </Row>
          <Row>
            <i-col span="12">
              <FormItem label="见证人姓名" prop="witnessName" style="margin-left: 40%">
                <Input type="text" size="default" v-bind:disabled="companyForm.disabled" v-model="companyForm.witnessName"
                  clearable placeholder="请输入" style="width: 200px" />
              </FormItem>
            </i-col>
            <i-col span="12">
              <FormItem label="见证人身份证号" prop="witnessIdCard" style="margin-left: 10%">
                <Input type="text" v-bind:disabled="companyForm.idCard" size="default" v-model="companyForm.witnessIdCard"
                  clearable placeholder="请输入" style="width: 200px" />
              </FormItem>
            </i-col>
          </Row>

          <Row>
            <i-col span="12">
              <Form-item label="见证人联系电话" prop="witnessContactNumber" style="margin-left: 40%">
                <Input type="text" v-bind:disabled="companyForm.disabled" size="default"
                  v-model="companyForm.witnessContactNumber" clearable placeholder="请输入" style="width: 200px;" maxlength="11" />
              </Form-item>
            </i-col>

            <i-col span="12">
              <Form-item label="有效期终止日期" prop="witnessValidityAuthorization" style="margin-left: 10%">
                <Date-picker type="date" size="default" v-bind:disabled="companyForm.disabled" :options="options3"
                  :value="companyForm.witnessValidityAuthorization" @on-change="companyForm.witnessValidityAuthorization=$event" placeholder="选择日期" style="width: 200px">
                </Date-picker>
              </Form-item>
            </i-col>
          </Row>

          <Row>
            <i-col span="12">
              <Form-item label="备注" prop="remake" style="margin-left: 40%">
                <Input ype="text" v-bind:disabled="companyForm.disabled" size="default" type="textarea" :rows="4"
                  v-model="companyForm.remake" clearable placeholder="请输入" style="width: 240%;" />
              </Form-item>
            </i-col>

          </Row>

          <Row >
            <i-col span="12">
              <Button @click="openFileUpload('companyForm')" size="large"
                style="margin-left: 45%;color: #2b85e4;   background-color:white;border: none">上传附件</Button>
            </i-col>
          </Row>
        </Form>
      </Row>
    </div>

    <div v-if="isShowFile">
      <!--附件-->
      <file-operation :uploadParam="uploadParam" :isInt="canUpload" :path="path" ></file-operation>
      
    </div>
    <div v-if="seeShowFile">
       <file-operation :uploadParam="uploadParam" :isInt="canUpload" :path="path" readOnly ></file-operation>
    </div>

    <Modal :title="modalTitle" v-model="black" :mask-closable='false' :width="500" :styles="{top: '100px'}">
      <Form ref="blackApplyForm" :model="blackApplyForm" :label-width="70">
        <FormItem label="申请原因" prop="blacklistReason">
          <Input v-model="blackApplyForm.blacklistReason" class="w400" size="large" placeholder="请输入黑名单申请原因"
            type="textarea" :rows="6" />
        </FormItem>
      </Form>
      <div slot="footer" style="text-align:center;">
        <Button type="text" @click="cancel">取消</Button>
        <Button type="primary" @click="join">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  channelSave,
  channelEdit,
  channelSaveBlack,
  getChannelWitnessById
} from "@/projects/afs-channel/api/witness/witness";
import { getChannelBaseInfo,getChannelId } from "@/projects/afs-apply/api/register-mng/listRecord";
import * as utils from "@/projects/afs-apply/assets/js/utils";
import timeUtils from "@/libs/util.js";
import {checkBlack} from "@/projects/afs-apply/api/affiliation/affiliationAddEdit";
import FileOperation from "_p/basic/pages/image/upload-file/fileOperation.vue";
import { checkFile } from "_p/basic/api/image/image-upload";
export default {
  name: "witness-add-edit",
  components: {
    FileOperation
  },
  data() {
    const validatePassword = (rule, value, callback) => {
      utils.doValidID(rule, value, callback);
      
    };
    const validateMobile = (rule, value, callback) => {
      var reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!reg.test(value)) {
        callback(new Error("手机号格式错误"));
      } else {
        callback();
      }
    };
    return {
      // 查看附件
      seeShowFile:false,
      // 附件上传的数据
      isShowFile:false,

      canUpload:false,
      uploadParam: {
                busiNo: "",
                belongNo: "witnessApply",
                busiType: "witnessApply",
                busiData: {}
            },
            path:"apply",
       // 控制不可以选的时间
    options3: {
                    disabledDate (date) {
                        return date && date.valueOf() < Date.now() - 86400000;
                    }
                },
      buttonSize: 'large',
      black: false, //是否显示黑名单申请对话框
      blackApplyForm: {
        blacklistReason: null // 申请黑名单原因
      },

      channelMessage:{}, // 被选中的数据合作商数据集合

      moveComment: false,

      loading: true,
      modalType: 0,
      modalTitle: "确认将合作商加入黑名单吗？",
      companyForm: {
        disabledNew: null,
        disabledOld: null,
        idCard: null,
        // 追加样式用的
        disabled: null,
        id: null,
        channelId: null, //渠道id
        businessAttributes: "0", // 新车还是二手车
        witnessName: null, // 见证人名字
        witnessIdCard: null, // 见证人 身份证
        witnessContactNumber: null, //见证人电话
        createTime: null, // 首次登记日期
        witnessValidityAuthorization: null, // 授权到期时间
        remake: null, // 备注
        status: null,
        channelBelong:null,   //渠道归属00:SP 01:直营 02:总对总
        firstReturn:'1',
      },

      // 存放合作商的集合
      baseInfo: [],

      // 下面用于表单必填验证
      ruleValidate: {
        channelId: [{ required: true, message: "请选择SP", trigger: "blur" }],

        witnessName: [
          { required: true, message: "请输入见证人姓名", trigger: "blur" }
        ],
        witnessIdCard: [
          { required: true, message: "请输入证件号", trigger: "blur" },
          { validator: validatePassword, trigger: "blur" }
        ],
        witnessContactNumber: [
          { required: true, message: "请输入正确是手机号", trigger: "blur" },
          { validator: validateMobile, trigger: "blur" }
        ],
        witnessValidityAuthorization: [
          {
            required: true,
            message: "请选择终止日期",
            trigger: "blur"
          }
        ]
      },

      submitLoading: false,
      total: 0
    };
  },
  // 加这个是为了刷新页面内容
  methods: {
    init() {
      this.getChannelId();
      if (this.afs.getPageParams(this).type == 1) {
      } else {
        this.companyForm.id = this.afs.getPageParams(this).id;
        if (this.afs.getPageParams(this).type == 2) {
          this.modalType = 2;
        } else if (this.afs.getPageParams(this).type == 3) {
          this.modalType = 3;
        }
        
      }
    },
    // 获取渠道id
    getChannelId(){
      // this.companyForm.channelId='4436432111308005376';
      //      this.getBaseInfo();
      getChannelId({}).then(res => {
        if (res.code === "0000") {
           this.companyForm.channelId = res.data;
            this.getBaseInfo();
        }
      });

    },
    // 通过id 查询这条信息
    getWitnessById() {
      getChannelWitnessById(this.companyForm)
        .then(res => {
          if (res.code === "0000") {
            this.companyForm = res.data;
            if (
              this.companyForm.status == "00" ||
              this.companyForm.status == "05"
            ) {
              this.companyForm.idCard = "disabled";
            }
            if (this.modalType == 3) {
              this.companyForm.disabledNew = "disabled";
              this.companyForm.disabledOld = "disabled";
              this.companyForm.disabled = "disabled";
              this.companyForm.idCard = "disabled";
            }
            this.carType();
            this.initGetFilterParams();
          }
        })
        .catch(() => {});
    },
    // 加入 黑名单
    joinBlack() {
      this.black = !this.black;
    },
    // 关闭黑名单申请
    cancel() {
      //关闭黑名单窗口
      this.black = false;
    },
    // 申请加入黑名单
    join() {
      if (
        this.companyForm.witnessName == null ||
        this.companyForm.witnessName == "" ||
        this.companyForm.witnessName == undefined
      ) {
        this.$Message.error("请输入姓名");
        return;
      }
      if (
        this.companyForm.witnessIdCard == null ||
        this.companyForm.witnessIdCard == "" ||
        this.companyForm.witnessIdCard == undefined
      ) {
        this.$Message.error("请输入证件号");
        return;
      }
      if (
        this.blackApplyForm.blacklistReason == null ||
        this.blackApplyForm.blacklistReason == "" ||
        this.blackApplyForm.blacklistReason == undefined
      ) {
        this.$Message.error("请输入申请原因");
        return;
      }
      let parms = {
        blacklistType: "03",
        blackName: this.companyForm.witnessName,
        idType: "01",
        idCode: this.companyForm.witnessIdCard,
        blacklistReason: this.blackApplyForm.blacklistReason
      };
      channelSaveBlack(parms)
        .then(res => {
          if (res.code === "0000") {
            this.$Message.success("申请成功！");
            this.joinBlack();
          }
        })
        .catch(() => {});
    },

    // 点击返回
    handleBack() {
      this.afs.closeTab(this);
    },
    // 点击提交
    handleCommit(name) {
      if(this.companyForm.businessAttributes=='0'){
        // 判断我是新车，那么我需要再去判断我是不是有新车属性
        if(this.channelMessage.businessType.toString().indexOf("01") != -1){
          }else{
          this.$Message.error("业务类型与权限不匹配");
          return;
        }
      }else{
        // 说明是二手车
        if(this.channelMessage.businessType.toString().indexOf("02") != -1){
          
        }else{
          this.$Message.error("业务类型与权限不匹配");
          return;
        }
      }
      var d = new Date(new Date().toLocaleDateString()).getTime()
      console.log(new Date(new Date().toLocaleDateString()))
      console.log(new Date(new Date().toLocaleDateString()).getTime());
      console.log(new Date(this.companyForm.witnessValidityAuthorization))
      var i = new Date(this.companyForm.witnessValidityAuthorization).getTime();
      
      this.companyForm.status = "01";
      this.$refs[name].validate(valid => {
        console.log(valid);
        // this.companyForm.witnessValidityAuthorization = timeUtils.formatDate(this.companyForm.witnessValidityAuthorization, 'YYYY-MM-DD hh:mm:ss');
        this.companyForm.witnessName=this.companyForm.witnessName.replace(/\s*/g,"");
        this.companyForm.witnessIdCard=this.companyForm.witnessIdCard.replace(/\s*/g,"");
        this.companyForm.witnessContactNumber=this.companyForm.witnessContactNumber.replace(/\s*/g,"");
        if(this.companyForm.remake!=null&&this.companyForm.remake!=undefined&&this.companyForm.remake!=""){
          this.companyForm.remake=this.companyForm.remake.replace(/\s*/g,"");
        }
        if (valid) {
          // 校验黑名单
          let params = {
              blacklistType: '03',
              idType: '01',
              idCode: this.companyForm.witnessIdCard,
          }
          checkBlack(params).then(res => {
              if (res.code === "0000") {
                  if (res.weatherBlackList == "0") {
                        console.log("3333333333")
          if (this.companyForm.id ==null||this.companyForm.id==undefined||this.companyForm.id=="") {
            this.$Message.error("请补全影像件信息！");
            //预审批信息录入
            // channelSave(this.companyForm)
            //   .then(res => {
            //     if (res.code === "0000") {
            //       this.$Message.success("操作成功");
            //       this.companyForm = res.data;
            //       // 先关闭本页面再跳转页面
            //       this.afs.closeTab(this);
            //     }
            //   })
            //   .catch(() => {});
          } else {
            checkFile(this.uploadParam).then(res => {
              if (res.code === '0000') {
                  // 修改预审批信息
                channelEdit(this.companyForm).then(res => {
                    if (res.code === "0000") {
                      this.$Message.success("修改成功");
                      this.companyForm = res.data;
                      // 先关闭本页面再跳转页面
                      this.afs.closeTab(this);
                    }
                  }).catch(() => {
                    
                  });
                }else{
                  this.$Message.error("请补全影像件信息！");
                }
            });
            
          }                    
                      } else {
                    this.$Message.error("见证人数据异常");
                }
              }
          });
           
        } else {
          this.$Message.error("请补全信息");
        }
      });
    },
    // 点击保存
    handle(name) {
      if(this.companyForm.businessAttributes=='0'){
        // 判断我是新车，那么我需要再去判断我是不是有新车属性
        if(this.channelMessage.businessType.toString().indexOf("01") != -1){
          }else{
          this.$Message.error("业务类型与权限不匹配");
          return;
        }
      }else{
        // 说明是二手车
        if(this.channelMessage.businessType.toString().indexOf("02") != -1){
          
        }else{
          this.$Message.error("业务类型与权限不匹配");
          return;
        }
      }
      var d = new Date(new Date().toLocaleDateString()).getTime()
      console.log(new Date(new Date().toLocaleDateString()))
      console.log(new Date(new Date().toLocaleDateString()).getTime());
      console.log(new Date(this.companyForm.witnessValidityAuthorization))
      var i = new Date(this.companyForm.witnessValidityAuthorization).getTime();
       
      this.$refs[name].validate(valid => {
        console.log(valid);
        // this.companyForm.witnessValidityAuthorization = timeUtils.formatDate(this.companyForm.witnessValidityAuthorization, 'YYYY-MM-DD hh:mm:ss');
        this.companyForm.witnessName=this.companyForm.witnessName.replace(/\s*/g,"");
        this.companyForm.witnessIdCard=this.companyForm.witnessIdCard.replace(/\s*/g,"");
        this.companyForm.witnessContactNumber=this.companyForm.witnessContactNumber.replace(/\s*/g,"");
        if(this.companyForm.remake!=null&&this.companyForm.remake!=undefined&&this.companyForm.remake!=""){
          this.companyForm.remake=this.companyForm.remake.replace(/\s*/g,"");
        }
        if (valid) {
          let params = {
              blacklistType: '03',
              idType: '01',
              idCode: this.companyForm.witnessIdCard,
          }
          checkBlack(params).then(res => {
              if (res.code === "0000") {
                  if (res.weatherBlackList == "0") {
          if (this.companyForm.id ==null||this.companyForm.id==undefined||this.companyForm.id=="") {
            this.companyForm.status='02';
            //预审批信息录入
            channelSave(this.companyForm)
              .then(res => {
                if (res.code === "0000") {
                  this.$Message.success("操作成功");
                  // 成功后吧数据重新赋值一次
                  this.companyForm.id=res.data.id;
                  this.getWitnessById();
                }
              })
              .catch(() => {});
          } else {
            checkFile(this.uploadParam).then(res => {
              if (res.code === '0000') {
                // 修改预审批信息
                  channelEdit(this.companyForm)
                    .then(res => {
                      if (res.code === "0000") {
                        this.$Message.success("操作成功");
                        this.companyForm.id=res.data.id;
                        this.getWitnessById();
                      }
                    }).catch(() => {

                    });
                }else{
                  this.$Message.error("请补全影像件信息！");
                }
            });
            
          }                       
                      } else {
                    this.$Message.error("见证人数据异常");
                }
              }
          });
          
        } else {
          this.$Message.error("请补全信息");
        }
      });
    },
    // 上传文件页面
    openFileUpload(name) {
       if(this.companyForm.id==null||this.companyForm.id==''||this.companyForm.id==undefined){
          if(this.companyForm.businessAttributes=='0'){
        // 判断我是新车，那么我需要再去判断我是不是有新车属性
        if(this.channelMessage.businessType.toString().indexOf("01") != -1){
          }else{
          this.$Message.error("业务类型与权限不匹配");
          return;
        }
      }else{
        // 说明是二手车
        if(this.channelMessage.businessType.toString().indexOf("02") != -1){
          
        }else{
          this.$Message.error("业务类型与权限不匹配");
          return;
        }
      }
      var d = new Date(new Date().toLocaleDateString()).getTime()
      console.log(new Date(new Date().toLocaleDateString()))
      console.log(new Date(new Date().toLocaleDateString()).getTime());
      console.log(new Date(this.companyForm.witnessValidityAuthorization))
      var i = new Date(this.companyForm.witnessValidityAuthorization).getTime();
       
      this.$refs[name].validate(valid => {
        console.log(valid);
        // this.companyForm.witnessValidityAuthorization = timeUtils.formatDate(this.companyForm.witnessValidityAuthorization, 'YYYY-MM-DD hh:mm:ss');
        this.companyForm.witnessName=this.companyForm.witnessName.replace(/\s*/g,"");
        this.companyForm.witnessIdCard=this.companyForm.witnessIdCard.replace(/\s*/g,"");
        this.companyForm.witnessContactNumber=this.companyForm.witnessContactNumber.replace(/\s*/g,"");
        if(this.companyForm.remake!=null&&this.companyForm.remake!=undefined&&this.companyForm.remake!=""){
          this.companyForm.remake=this.companyForm.remake.replace(/\s*/g,"");
        }
        if (valid) {
          let params = {
              blacklistType: '03',
              idType: '01',
              idCode: this.companyForm.witnessIdCard,
          }
          checkBlack(params).then(res => {
              if (res.code === "0000") {
                  if (res.weatherBlackList == "0") {
                      if (this.companyForm.id ==null||this.companyForm.id==undefined||this.companyForm.id=="") {
                        this.companyForm.status='02';
                        //预审批信息录入
                        channelSave(this.companyForm)
                          .then(res => {
                            if (res.code === "0000") {
                              this.$Message.success("操作成功");
                              // 成功后吧数据重新赋值一次
                              this.companyForm.id=res.data.id;
                              // 调后台获取json
                              this.initGetFilterParams();
                              console.log(this.isShowFile);
                              if(this.modalType!='03'){
                                this.isShowFile = !this.isShowFile;
                              }else{
                                this.seeShowFile = !this.seeShowFile;
                              }
                            }
                          })
                          .catch(() => {});
                      }                       
                    } else {
                    this.$Message.error("见证人数据异常");
                }
              }
          });
          
        } else {
          this.$Message.error("请补全信息");
        }
      });
      }else{
        // 调后台获取json
        this.initGetFilterParams();
        console.log(this.isShowFile);
        if(this.modalType!='03'){
          this.isShowFile = !this.isShowFile;
        }else{
          this.seeShowFile = !this.seeShowFile;
        }
      }
    },
    // 获取附件数据
    initGetFilterParams() {
      console.log(this.companyForm.id)
            this.uploadParam.busiNo = this.companyForm.id;
            this.uploadParam.belongNo = "witnessApply";
            this.uploadParam.busiData = {};
            this.uploadParam.busiType = "witnessApply";
            this.canUpload=true;
        },

    // 获取合作商信息接口
    getBaseInfo() {
      getChannelBaseInfo({status:"00"}).then(res => {
        this.loading = false;
        if (res.code === "0000") {
          this.baseInfo = res.data;
          if(this.baseInfo.length>0){
            for (var i = 0; i < this.baseInfo.length; i++){
                if (this.companyForm.channelId == this.baseInfo[i].id) {
                  this.channelMessage =this.baseInfo[i];
                  this.companyForm.channelBelong = this.baseInfo[i].channelBelong;
                  break;
                }
            }
          }
          console.log("我等于及："+this.modalType)
          
            this.carType();
            if(this.modalType=="0"){

            }else{
              this.getWitnessById();
            }
            
        }
      });
    },
    // 写个方法去判断进来的新车二手车权限
    carType(){
      if (this.baseInfo.length > 0) {
              for (var i = 0; i < this.baseInfo.length; i++) {
                console.log("w yao kan"+this.companyForm.channelId)
                console.log("集合的"+this.baseInfo[i].id)
                if (this.companyForm.channelId == this.baseInfo[i].id) {
                  var type = this.baseInfo[i].businessType;
                  var typeList = type.split(",");
                  console.log("我的业务类型：" + type);
                  if (typeList.length > 0) {
                    if (typeList.length == 1) {
                      if (typeList[0] == "01") {
                        console.log("这是新车")
                        this.companyForm.disabledOld = "disabled";
                        this.companyForm.disabledNew = null;
                        this.companyForm.businessAttributes = "0";
                      } else if (typeList[0] == "02") {
                        console.log("这是二手车")
                        this.companyForm.disabledOld = null;
                        this.companyForm.disabledNew = "disabled";
                        this.companyForm.businessAttributes = "1";
                      }
                    } else if (typeList.length == 2) {
                      this.companyForm.disabledOld = null;
                      this.companyForm.disabledNew = null;
                    }
                  }
                }
              }

              if (
              this.companyForm.status == "00" ||
              this.companyForm.status == "05"||this.companyForm.status == "03"
            ) {
              if(this.companyForm.firstReturn=='0'){
                this.companyForm.idCard = "disabled";
                this.companyForm.disabledNew = "disabled";
                this.companyForm.disabledOld = "disabled";
              }
            }
            }
    },
  },
  // 初始化加载
  mounted() {
    this.init();
  }
};
</script>
